package com.garlicts.framework.base.response;

import java.io.Serializable;

import com.garlicts.framework.base.code.CommonCode;
import com.garlicts.framework.base.code.ICode;

public class Response<T> implements Serializable {

	private static final long serialVersionUID = -8196590103850895806L;

	private int code;
    private String msg;
    private T data;

    public Response() {
    }

    public Response(ICode commonCode) {
        this.code = commonCode.getCode();
        this.msg = commonCode.getMsg();
    }

    public Response(int code, String msg) {
        this.code = code;
        this.msg = msg;
    }

    public Response(int code, String msg, T data) {
        this.code = code;
        this.msg = msg;
        this.data = data;
    }

    public Response<T> setICode(ICode code) {
        this.code = code.getCode();
        this.msg = code.getMsg();
        return this;
    }

    public int getCode() {
        return this.code;
    }

    public Response<T> setCode(int code) {
        this.code = code;
        return this;
    }

    public String getMsg() {
        return this.msg;
    }

    public Response<T> setMsg(String msg) {
        this.msg = msg;
        return this;
    }

    public T getData() {
        return this.data;
    }

    public Response<T> setData(T data) {
        this.data = data;
        return this;
    }

    public boolean success() {
        return this.code == CommonCode.SUCCESS.getCode();
    }

    public boolean isCode(ICode code) {
        return this.code == code.getCode();
    }

    public static <T> Response<T> newSuccessResponse(T result) {
        return newResponse(result, CommonCode.SUCCESS);
    }

    public static <T> Response<T> newFailResponse(ICode icode) {
        return newResponse(null, icode);
    }

    public static <T> Response<T> newFailResponse(int code, String msg) {
        Response<T> r = new Response<T>();
        r.code = code;
        r.msg = msg;
        return r;
    }

    private static <T> Response<T> newResponse(T result, ICode icode) {
        Response<T> r = new Response<T>();
        r.code = icode.getCode();
        r.msg = icode.getMsg();
        r.data = result;
        return r;
    }
	
}
